package com.neusoft.neuiotms.dcom.repository.impl;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.model.Holiday;
import com.neusoft.neuiotms.dcom.model.QHoliday;
import com.neusoft.neuiotms.dcom.repository.CustomizedHolidayRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedHolidayRepositoryImpl extends AbstractRepository implements CustomizedHolidayRepository {

    @Override
    public List<Holiday> index(final Searchable searchable) {
        final QHoliday qHoliday = QHoliday.holiday;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Holiday> query = this.query().selectFrom(qHoliday);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Page<Holiday> search(final Pageable pageable, final Searchable searchable) {
        final QHoliday qHoliday = QHoliday.holiday;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Holiday> query = this.query().selectFrom(qHoliday);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return Holiday.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {

        final BooleanBuilder where = new BooleanBuilder();
        final QHoliday qHoliday = QHoliday.holiday;

        // 名称检索
        where.and(super.containsStr(qHoliday.name, searchable, "name"));
        // 类型
        where.and(super.equalsStr(qHoliday.type, searchable, "type"));
        // 日期检索时间段
        where.and(super.afterOrEqualsDate(qHoliday.date, searchable, "startTime"));
        where.and(super.beforeOrEqualsDate(qHoliday.date, searchable, "endTime"));

        return where;
    }
}
